package com.xnyzc.lhy.resource.util.oss;

import com.alibaba.fastjson.JSONObject;
import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.OSSObject;
import com.xnyzc.lhy.common.penum.EOSSErrorCode;
import com.xnyzc.lhy.common.util.DateUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.ByteArrayInputStream;
import java.net.URL;
import java.util.Date;

@Slf4j
@Service
public class AliyunOSS implements IOSS {

    @Value("${global.ali.oss.endpoint}")
    private String endpoint;

    @Value("${global.ali.oss.accessKeyId}")
    private String accessKeyId;

    @Value("${global.ali.oss.accessKeySecret}")
    private String accessKeySecret;

    @Value("${global.ali.oss.bucketName}")
    private String bucketName;

    @Value("${global.ali.oss.validityTime}")
    private Integer validityTime;

    private  OSS ossClient = null;

    @Override
    public void Initializtion()
    {
        try{
            ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        }catch (Exception exception) {
            log.error("阿里云对象存储参数初始化错误");
            throw com.xnyzc.lhy.common.exception.OSSException.create(EOSSErrorCode.initializtionError);
        }
    }

    @Override
    public void uploadFile(String key, byte[] content) {
        try{
            // 创建OSSClient实例。
            ossClient.putObject(bucketName, key, new ByteArrayInputStream(content));
        }catch (OSSException ossException) {
            log.error("阿里云对象存储服务器端错误");
            throw com.xnyzc.lhy.common.exception.OSSException.create(EOSSErrorCode.serverError);
        } catch (ClientException clientException) {
            log.error("案例云对象存储客户端错误");
            throw com.xnyzc.lhy.common.exception.OSSException.create(EOSSErrorCode.clientError);
        }
    }

    @Override
    public URL getFileUrl(String key) {
        URL url = null;
        try{
            // 设置URL过期时间时间（单位分钟）。
            Date expiration = DateUtil.dateAddMinutes(new Date(), validityTime);
            // 生成以GET方法访问的签名URL，访客可以直接通过浏览器访问相关内容。
            url = ossClient.generatePresignedUrl(bucketName, key, expiration);
        }catch (OSSException ossException) {
            log.error("阿里云对象存储服务器端错误");
            throw com.xnyzc.lhy.common.exception.OSSException.create(EOSSErrorCode.serverError);
        } catch (ClientException clientException) {
            log.error("阿里云对象存储客户端错误");
            throw com.xnyzc.lhy.common.exception.OSSException.create(EOSSErrorCode.clientError);
        }

        return url;
    }

    @Override
    public boolean getFileMessage(String key) {
        try {
            OSSObject object = ossClient.getObject(bucketName, key);
        } catch (Exception e) {
            log.error("查询存储对象失败！错误为：{}", e.toString());
            return false;
        }
        return true;
    }

    @Override
    public void shutdown() {
        if (ossClient != null ) {
            ossClient.shutdown();
        }
    }

    /**
     * 获取动态秘钥（暂无）
     */
    @Override
    public JSONObject getTemporary() {
        return null;
    }

    /**
     * 获取 uploadId（暂无）
     * @param savePath 保存路径
     * @return String
     */
    @Override
    public String getUploadId(String savePath) {
        return null;
    }
}
